<template>
  <div class="app-container">
    <el-card class="box-card search-div" v-show="showSearch">
      <el-form :inline="true" :model="listQuery" ref="queryForm">
        <el-form-item label="区划编号">
          <el-input v-model="listQuery.code" :maxlength="12" clearable></el-input>
        </el-form-item>
        <el-form-item label="区划名称">
          <el-input v-model="listQuery.name" :maxlength="32" clearable></el-input>
        </el-form-item>
        <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
        <el-button @click="handleResetQuery" icon="el-icon-refresh">重置</el-button>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" v-hasPermi="['region_sysRegion_add']" class="el-icon-plus" @click="add">新增</el-button>
        <el-button type="danger" class="el-icon-delete" @click="cleanCache">更新缓存</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </div>
      <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row class="table-list">
        <el-table-column label="序号" type="index" min-width="5%" />
        <el-table-column align="center" label="区划编号" prop="code" />
        <el-table-column align="center" label="区划名称" prop="name" />
        <el-table-column align="center" label="父区划" prop="parentName" />
        <el-table-column align="center" label="层级" prop="level" :formatter="levelFormat" />
        <el-table-column align="center" label="经纬度" prop="lnglat" />
        <el-table-column align="center" label="修改时间" prop="updateTime" width="150px"></el-table-column>
        <el-table-column align="center" label="操作" width="260" fixed="right">
          <template slot-scope="scope">
            <el-button plain v-hasPermi="['region_sysRegion_edit']" type="violet" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button plain v-hasPermi="['region_sysRegion_add']" type="primary" @click="handleAdd(scope.$index, scope.row)">添加下级</el-button>
            <el-button plain v-hasPermi="['region_sysRegion_remove']" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </el-card>

    <!--弹出框-->
    <el-dialog :title="dialogTitle" :width="'600px'" :visible.sync="showDialog" :close-on-click-modal="false">
      <el-form :rules="rules" ref="savesysRegionData" :model="savesysRegionData" label-width="100px">
        <el-form-item label="区划编号:" prop="code">
          <el-input v-model="savesysRegionData.code" :maxlength="12" placeholder="最多输入12个字符" clearable show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="区划名称:" prop="name">
          <el-input v-model="savesysRegionData.name" :maxlength="32" placeholder="最多输入32个字符" clearable show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="父区划:" prop="parentName" v-if="hasChild">
          <el-input v-model="savesysRegionData.parentName" :maxlength="12" placeholder="最多输入12个字符" clearable
            show-word-limit disabled></el-input>
        </el-form-item>
        <el-form-item label="层级:" prop="level">
          <el-select v-model="savesysRegionData.level" placeholder="请选择层级" clearable style="width: 100%;">
            <el-option v-for="dict in levelOptions" :key="dict.dictKey" :label="dict.dictValue" :value="parseInt(dict.dictKey)" />
          </el-select>
        </el-form-item>
        <el-form-item label="经纬度:" prop="lnglat">
          <el-input v-model="savesysRegionData.lnglat" :maxlength="20" placeholder="最多输入20个字符" clearable
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="排序:" prop="orderNum">
          <el-input-number v-model="savesysRegionData.orderNum" :min="0" :max="999999" style="width: 100%;"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave('savesysRegionData')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as sysRegion from './js/region'
  import { mapGetters } from 'vuex'

  export default {
    name: 'regionList',
    data() {
      return {
        list: null,
        // 遮罩层
        listLoading: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        listQuery: {
          page: 1,
          limit: 10,
          code: '',
          name: '',
        },
        levelOptions: [],
        showDialog: false,
        savesysRegionData: {
          id: '',
          code: '',
          name: '',
          parentCode: '',
          parentName: '顶级',
          level: '',
          lnglat: '',
          orderNum: '',
        },
        rules: {
          code: [{
            required: true,
            message: '请输入区划编号',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '请输入区划名称',
            trigger: 'blur'
          }],
          level: [{
            required: true,
            message: '请输入层级',
            trigger: 'blur'
          }],
        },
        hasChild: false,
        dialogTitle: '添加行政区划'
      }
    },
    computed: {
      ...mapGetters(['permissions'])
    },
    created() {
      this.init()
      this.getList()
    },
    methods: {
      // 字典列表初始
      init() {
        this.getDictByCode("region").then(response => {
          this.levelOptions = response.data;
        });
      },
      // 字典值列表显示
      levelFormat(row, column) {
        return this.selectDictLabel(this.levelOptions, row.level);
      },
      getList() { // 获取所有行政区划
        this.listLoading = true
        sysRegion.list(this.listQuery).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleSearch() {
        this.listQuery.page = 1
        this.getList()
      },
      handleResetQuery() {
        this.resetForm("queryForm")
        this.handleSearch()
      },
      //删除
      handleDelete(id) {
        this.$confirm('请确定是否删除该数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sysRegion.removeByIds(id).then((response) => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          })
        }).catch(function(error) {
          console.log(error)
        })
      },
      // 新增
      add() {
        this.showDialog = true
        this.dialogTitle = '添加行政区划'
        // 清空表单数据
        this.$nextTick(() => {
          this.resetForm('savesysRegionData')
          this.savesysRegionData.level = 0
        })
      },
      // 编辑
      handleEdit(index, row) {
        this.showDialog = true
        this.dialogTitle = '编辑行政区划'
        this.$nextTick(() => {
          this.resetForm('savesysRegionData')
          // 需要拷贝一下，不然会清空列表
          let tmpRow = JSON.parse(JSON.stringify(row));
          this.savesysRegionData = tmpRow
          this.hasChild = true
        })
      },
      //添加子
      handleAdd(index,row){
        this.showDialog = true
        this.hasChild = true
        this.dialogTitle = '添加行政区划'
        // 清空表单数据
        this.$nextTick(() => {
          this.resetForm('savesysRegionData')
          this.savesysRegionData.parentCode = row.code
          this.savesysRegionData.parentName = row.name
          this.savesysRegionData.level = row.level+1
        })
      },
      // 更新缓存
      cleanCache(formName) {
        sysRegion.cleanCache().then((response) => {
          this.$message({type: 'success',message: '操作成功!'})
          this.getList()
        }).catch(function(error) {
              console.log(error)
        })
      },
      // 保存
      onSave(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            sysRegion.editSave(this.savesysRegionData).then((response) => {
              this.$message({type: 'success',message: '操作成功!'})
              this.getList()
              this.showDialog = false
            }).catch(function(error) {
              console.log(error)
            })
          }
        })
      }
    }
  }
</script>
